package cn.dylan.filters;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class ZuulPreFilter extends ZuulFilter {
    // 这个拦截器是什么拦截器，确定作用时机
    @Override
    public String filterType() {
        return "pre";
    }

    //优先级
    @Override
    public int filterOrder() {
        return 0;
    }

    // 返回值为FALSE的时候 下面的run方法不执行  用作放行
    @Override
    public boolean shouldFilter() {
        // 获取上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        // 获取请求uri
        String uri = context.getRequest().getRequestURI();

        if (StringUtils.endsWithIgnoreCase(uri,"login")
        || StringUtils.endsWithIgnoreCase(uri,"register")) {
            return false;
        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletResponse response = context.getResponse();
        String token = context.getRequest().getHeader("token");
        if(StringUtils.isEmpty(token)){
            try {
                // token不存在，没有登录 返回前端未登录。nologin

                Map<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("msg","noLogin");
                PrintWriter writer = response.getWriter();
                //把map转成json格式字符串
                String s = JSONObject.toJSONString(map);
                // 响应给前端
                writer.write(s);
                context.setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 返回的任意值 表示继续
        return 1;
    }
}
